import React, { useState, useEffect } from 'react';
import { Progress, Typography, Space, Spin } from 'antd';
import { CheckCircleOutlined, LoadingOutlined } from '@ant-design/icons';

// 添加CSS动画
const styles = `
  @keyframes pulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.05); }
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  @keyframes fadeInUp {
    0% { 
      opacity: 0; 
      transform: translateY(20px); 
    }
    100% { 
      opacity: 1; 
      transform: translateY(0); 
    }
  }
`;

// 注入样式
if (typeof document !== 'undefined') {
  const styleSheet = document.createElement('style');
  styleSheet.textContent = styles;
  document.head.appendChild(styleSheet);
}

const { Text, Title } = Typography;

interface InitializationStep {
  id: string;
  name: string;
  description: string;
  duration: number;
}

interface InitializationProgressProps {
  visible: boolean;
  onComplete: () => void;
}

const InitializationProgress: React.FC<InitializationProgressProps> = ({ 
  visible, 
  onComplete 
}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [progress, setProgress] = useState(0);
  const [completedSteps, setCompletedSteps] = useState<string[]>([]);

  const steps: InitializationStep[] = [
    {
      id: 'auth',
      name: '验证身份',
      description: '正在验证您的登录信息...',
      duration: 800
    },
    {
      id: 'profile',
      name: '加载用户资料',
      description: '正在获取您的个人信息...',
      duration: 600
    },
    {
      id: 'settings',
      name: '初始化设置',
      description: '正在加载个人设置...',
      duration: 500
    },
    {
      id: 'data',
      name: '同步数据',
      description: '正在同步您的学习数据...',
      duration: 700
    },
    {
      id: 'complete',
      name: '完成初始化',
      description: '系统准备就绪！',
      duration: 400
    }
  ];

  useEffect(() => {
    console.log('InitializationProgress visible:', visible);
    if (!visible) {
      setCurrentStep(0);
      setProgress(0);
      setCompletedSteps([]);
      return;
    }

    let isMounted = true;
    let currentProgress = 0;
    const completed: string[] = [];

    const runInitialization = async () => {
      for (let i = 0; i < steps.length; i++) {
        if (!isMounted) break;
        
        setCurrentStep(i);
        
        // 计算当前步骤的进度增量
        const stepProgress = (100 / steps.length);
        const targetProgress = (i + 1) * stepProgress;
        
        // 逐步增加进度
        const progressInterval = setInterval(() => {
          if (!isMounted) {
            clearInterval(progressInterval);
            return;
          }
          currentProgress += stepProgress / (steps[i].duration / 50);
          if (currentProgress >= targetProgress) {
            currentProgress = targetProgress;
            clearInterval(progressInterval);
          }
          setProgress(Math.min(currentProgress, 100));
        }, 50);

        // 等待当前步骤完成
        await new Promise(resolve => setTimeout(resolve, steps[i].duration));
        clearInterval(progressInterval);
        
        if (!isMounted) break;
        
        // 标记步骤完成
        completed.push(steps[i].id);
        setCompletedSteps([...completed]);
        setProgress(targetProgress);
      }

      if (isMounted) {
        // 初始化完成
        setTimeout(() => {
          if (isMounted) {
            onComplete();
          }
        }, 500);
      }
    };

    runInitialization();

    return () => {
      isMounted = false;
    };
  }, [visible]);

  if (!visible) return null;

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      zIndex: 9999,
      color: 'white'
    }}>
      {/* Logo和标题 */}
      <div style={{ textAlign: 'center', marginBottom: '40px' }}>
        <div style={{
          fontSize: '48px',
          marginBottom: '20px',
          animation: 'pulse 2s ease-in-out infinite',
          animationDelay: '0.5s'
        }}>
          📚
        </div>
        <Title level={2} style={{ color: 'white', marginBottom: '10px' }}>
          LinkMate
        </Title>
        <Text style={{ color: 'rgba(255, 255, 255, 0.8)', fontSize: '16px' }}>
          正在为您准备学习环境...
        </Text>
      </div>

      {/* 进度条 */}
      <div style={{ width: '400px', marginBottom: '30px' }}>
        <Progress
          percent={Math.round(progress)}
          strokeColor={{
            '0%': '#108ee9',
            '100%': '#87d068',
          }}
          trailColor="rgba(255, 255, 255, 0.2)"
          strokeWidth={8}
          showInfo={true}
          format={(percent) => `${percent}%`}
        />
      </div>

      {/* 当前步骤 */}
      {currentStep < steps.length && (
        <div style={{ textAlign: 'center', marginBottom: '30px' }}>
          <Space direction="vertical" size="small">
            <div style={{ fontSize: '18px', fontWeight: 'bold' }}>
              {steps[currentStep].name}
            </div>
            <div style={{ fontSize: '14px', opacity: 0.8 }}>
              {steps[currentStep].description}
            </div>
          </Space>
        </div>
      )}

      {/* 步骤列表 */}
      <div style={{ width: '400px' }}>
        {steps.map((step, index) => (
          <div
            key={step.id}
            style={{
              display: 'flex',
              alignItems: 'center',
              padding: '8px 0',
              borderBottom: index < steps.length - 1 ? '1px solid rgba(255, 255, 255, 0.1)' : 'none',
              opacity: index <= currentStep ? 1 : 0.5,
              animation: index <= currentStep ? 'fadeInUp 0.5s ease-out' : 'none',
              animationDelay: `${index * 0.1}s`
            }}
          >
            <div style={{ marginRight: '12px', width: '20px' }}>
              {completedSteps.includes(step.id) ? (
                <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '16px' }} />
              ) : index === currentStep ? (
                <Spin indicator={<LoadingOutlined style={{ color: 'white', fontSize: '16px' }} />} />
              ) : (
                <div style={{ width: '16px', height: '16px', borderRadius: '50%', background: 'rgba(255, 255, 255, 0.3)' }} />
              )}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: '14px', fontWeight: index <= currentStep ? 'bold' : 'normal' }}>
                {step.name}
              </div>
              {index === currentStep && (
                <div style={{ fontSize: '12px', opacity: 0.7, marginTop: '2px' }}>
                  {step.description}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* 底部提示 */}
      <div style={{ marginTop: '30px', textAlign: 'center', opacity: 0.7 }}>
        <Text style={{ fontSize: '12px' }}>
          请稍候，我们正在为您优化体验...
        </Text>
      </div>
    </div>
  );
};

export default InitializationProgress;
